package com.eage.security.login.impl;


import com.eage.security.domain.ShiroUserDetail;
import com.eage.security.properties.CompanyProperties;
import com.eage.security.login.ShiroUserDetailService;
import com.eage.security.login.inter.UserLogin;
import com.eage.security.utils.ShiroEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: lex
 * @Date: 2019/2/1
 */
@Slf4j
@Component
public class FormUserLoginImpl implements UserLogin {


    @Autowired
    private CompanyProperties companyProperties;

    @Resource
    private ShiroUserDetailService shiroUserDetailServiceImpl;

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(UsernamePasswordToken token) throws AuthenticationException {
        log.warn("现在为表单登入");
        ShiroUserDetail shiroUserDetail = this.getUserDetail(token);
        token.setPassword(ShiroEncrypt.md5AndSha(new String(token.getPassword())).toCharArray());
        return new SimpleAuthenticationInfo(shiroUserDetail, shiroUserDetail.getPassword(), shiroUserDetail.getUserId());
    }

    @Override
    public ShiroUserDetail getUserDetail(UsernamePasswordToken token) throws AuthenticationException {
        String username = token.getUsername().split(":" + companyProperties.getLoginSplit() + ":")[1];
        return shiroUserDetailServiceImpl.getByUserName(username);
    }

}
